package com.parser;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.*;

/**
 * @author rkc
 * @date 2022/8/28 10:47
 */
public class PomXmlParser {

    private SAXReader saxReader = new SAXReader();
    private Document document;
    private Map<String, List<Element>> elementMap = new HashMap<>();

    public PomXmlParser(String path) throws DocumentException {
        document = saxReader.read(new File(path));
        parse();
    }

    private void parse() {
        Element rootElement = document.getRootElement();
        parse(rootElement, rootElement.getName());
    }

    private void parse(Element element, String prefix) {
        Iterator<Element> iterator = element.elementIterator();
        while (iterator.hasNext()) {
            Element next = iterator.next();
            if (next.getName().trim().length() == 0) {
                continue;
            }
            if (next.getText().trim().length() != 0) {
                String key = String.format("%s.%s", prefix, next.getName());
                List<Element> elements = elementMap.getOrDefault(key, new ArrayList<>());
                elements.add(next);
                elementMap.put(key, elements);
            }
            parse(next, prefix + "." + next.getName());
        }
    }

    public Map<String, List<Element>> getElementMap() {
        return elementMap;
    }

    public Element getElementOne(String key) {
        return getElements(key).get(0);
    }

    public List<Element> getElements(String key) {
        return elementMap.get(key);
    }
}
